import { useMobx } from "@whzhuke/mobx"
import { Button, Col, Row, Select, Space, Typography, message as antdMessage, Badge, Modal } from "antd"
import { MessageOutlined, DownOutlined } from "@ant-design/icons"
import React, { useCallback, useState, useEffect, useContext } from "react"
import messageService from "@/services/message.service"
import { DateRender } from "@whzhuke/antd"
import { StoreContext } from "@/store"
import { functionCommon } from "@whzhuke/common"

const { Text, Link } = Typography
const formatTime = DateRender("YYYY-MM-DD HH:mm:ss")
const normalizeReadFlag = (flag: any) => {
  if (flag === 1 || flag === "1" || flag === true) return 1
  return 0
}

const filterMessages = (data: any[] = [], type: string) => {
  if (!Array.isArray(data)) return []
  let filtered = data
  if (type === "read") {
    filtered = data.filter((item: any) => normalizeReadFlag(item.readFlag) === 1)
  } else if (type === "unread") {
    filtered = data.filter((item: any) => normalizeReadFlag(item.readFlag) === 0)
  }
  return filtered.map(item => ({ ...item }))
}

const contentFieldLabels: Record<string, string> = {
  contractCode: "合同编号",
  contractName: "合同名称",
  contractFileUrl: "合同文件",
  createdBy: "创建人",
  createTs: "创建时间",
  updateTs: "更新时间"
}

const parseContentEntries = (content: any) => {
  if (!content) return null
  let parsed = content
  if (typeof content === "string") {
    try {
      parsed = JSON.parse(content)
    } catch {
      parsed = null
    }
  }
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
    return Object.entries(parsed)
  }
  return null
}

const Page = useMobx(() => {
  const { UserStore } = useContext(StoreContext)
  const [rawMessages, setRawMessages] = useState<any[]>([])
  const [messageList, setMessageList] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [messageType, setMessageType] = useState("all")
  const [expandedMessages, setExpandedMessages] = useState<Record<string | number, boolean>>({})

  const previewAttachment = useCallback((fileUrl?: string) => {
    if (!fileUrl) {
      Modal.warning({
        title: "提示",
        content: "暂无可预览的附件"
      })
      return
    }
    const viewerOrigin = window.location.origin
    const previewBase = `${viewerOrigin}/web/viewer.html?file=`
    const normalizedUrl = functionCommon.requestHost("public") + fileUrl
    const previewUrl = `${previewBase}${encodeURIComponent(normalizedUrl)}`
    window.open(previewUrl, "_blank")
  }, [])

  const loadMessages = useCallback(async () => {
    setLoading(true)
    try {
      const uid = UserStore.user?.id ?? UserStore.user?.uid
      if (!uid) {
        antdMessage.warning("无法获取当前用户信息，请重新登录后再试")
        setRawMessages([])
        setMessageList([])
        return
      }
      const params: Record<string, any> = { uid }
      if (messageType === "read") {
        params.readFlag = 1
      } else if (messageType === "unread") {
        params.readFlag = 0
      }
      const response = await messageService.list(params)
      const list = response.data?.list || response.data || []
      setRawMessages(list)
      setMessageList(filterMessages(list, messageType))
    } catch (error) {
      console.error("加载消息列表失败:", error)
      antdMessage.error("加载消息列表失败")
      setMessageList(prev => filterMessages(prev || [], messageType))
    } finally {
      setLoading(false)
    }
  }, [UserStore, messageType])

  useEffect(() => {
    setMessageList(filterMessages(rawMessages, messageType))
  }, [rawMessages, messageType])

  useEffect(() => {
    loadMessages()
  }, [loadMessages])

  const handleMarkAllRead = useCallback(async () => {
    const uid = UserStore.user?.id ?? UserStore.user?.uid
    if (!uid) {
      antdMessage.warning("无法获取当前用户信息，请重新登录后再试")
      return
    }
    const unreadItems = rawMessages.filter(item => normalizeReadFlag(item.readFlag) === 0 && item.bid)
    if (unreadItems.length === 0) {
      antdMessage.info("暂无可标记的消息")
      return
    }
    try {
      await Promise.all(
        unreadItems.map(item =>
          messageService.seen({
            bid: item.bid,
            uid,
            readFlag: true
          })
        )
      )
      antdMessage.success("已标记全部已读")
      setRawMessages(prev => prev.map(item => ({ ...item, readFlag: 1 })))
      loadMessages()
    } catch (error) {
      console.error("标记全部已读失败:", error)
      antdMessage.error("标记全部已读失败")
    }
  }, [UserStore, messageList, loadMessages])

  const handleViewMessage = useCallback(
    async (item: any) => {
      const uid = UserStore.user?.id ?? UserStore.user?.uid
      if (!uid) {
        antdMessage.warning("无法获取当前用户信息，请重新登录后再试")
        return
      }
      try {
        await messageService.seen({
          bid: item.bid,
          uid,
          readFlag: true
        })
        setRawMessages(prev => prev.map(msg => (msg.id === item.id || msg.bid === item.bid ? { ...msg, readFlag: 1 } : msg)))
        loadMessages()
      } catch (error) {
        console.error("查看消息失败:", error)
        antdMessage.error("查看消息失败")
      }
    },
    [UserStore, loadMessages]
  )

  const toggleExpand = useCallback(
    async (item: any, key: string | number, expand: boolean) => {
      setExpandedMessages(prev => ({ ...prev, [key]: expand }))
      if (expand && !item.readFlag) {
        await handleViewMessage(item)
      }
    },
    [handleViewMessage]
  )

  return (
    <div style={{ padding: 24, background: "#fff" }}>
      <Row justify="space-between" align="middle" style={{ marginBottom: 16, paddingBottom: 16, borderBottom: "1px solid #e8e8e8" }}>
        <Col>
          <Text strong style={{ fontSize: 16 }}>
            消息列表
          </Text>
        </Col>
        <Col>
          <Space size="middle">
            <Button type="primary" onClick={handleMarkAllRead}>
              标记全部已读
            </Button>
            <Select
              value={messageType}
              onChange={setMessageType}
              style={{ width: 120 }}
              suffixIcon={<DownOutlined />}
              options={[
                { label: "全部消息", value: "all" },
                { label: "未读消息", value: "unread" },
                { label: "已读消息", value: "read" }
              ]}
            />
          </Space>
        </Col>
      </Row>
      {loading ? (
        <div style={{ textAlign: "center", padding: "40px 0", color: "#999" }}>加载中...</div>
      ) : messageList.length === 0 ? (
        <div style={{ textAlign: "center", padding: "40px 0", color: "#999" }}>暂无消息</div>
      ) : (
        messageList.map((item, index) => {
          const messageKey = item.id ?? item.bid ?? index
          const isExpanded = !!expandedMessages[messageKey]
          const entries = parseContentEntries(item.content)
          const contentMap = entries ? Object.fromEntries(entries) : null
          const contractName = contentMap?.contractName || item.contractName || "发件人"
          const contractBy = contentMap?.contractBy || contentMap?.createdBy || item.contractBy || item.createdBy || contractName
          const summaryText = `收到${contractBy}的消息`

          return (
            <Row
              key={messageKey}
              align="middle"
              style={{
                padding: "16px 0",
                borderBottom: index < messageList.length - 1 ? "1px solid #e8e8e8" : "none"
              }}
            >
              <Col flex="none" style={{ marginRight: 16 }}>
                <Badge dot={!item.readFlag} color="#ff4d4f" offset={[8, -8]}>
                  <MessageOutlined style={{ fontSize: 24, color: "#8c8c8c" }} />
                </Badge>
              </Col>
              <Col flex="auto">
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <Text strong style={{ display: "block", marginBottom: 0 }}>
                    {isExpanded ? item.message || summaryText : summaryText}
                  </Text>
                  <Link
                    onClick={e => {
                      e.preventDefault()
                      e.stopPropagation()
                      toggleExpand(item, messageKey, !isExpanded)
                    }}
                  >
                    {isExpanded ? "收起" : "立即查看"}
                  </Link>
                </div>
                {isExpanded &&
                  (entries ? (
                    <div style={{ marginTop: item.message ? 4 : 0 }}>
                      {entries.map(([key, value]) => (
                        <div key={key} style={{ fontSize: 12, color: "#595959", marginTop: 2 }}>
                          <span style={{ color: "#8c8c8c", marginRight: 4 }}>{contentFieldLabels[key] || key}：</span>
                          {key === "contractFileUrl" && typeof value === "string" ? (
                            (() => {
                              const fileUrl = value
                              const extTarget = fileUrl.split("?")[0]?.toLowerCase() || ""
                              const isPdf = extTarget.endsWith(".pdf")
                              if (isPdf) {
                                return (
                                  <Button
                                    type="link"
                                    onClick={e => {
                                      e.stopPropagation()
                                      previewAttachment(fileUrl)
                                    }}
                                    style={{ padding: 0 }}
                                  >
                                    查看附件
                                  </Button>
                                )
                              }
                              const downloadUrl = `${functionCommon.requestHost("public")}${fileUrl}`
                              return downloadUrl ? (
                                <Link href={downloadUrl} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()}>
                                  下载附件
                                </Link>
                              ) : (
                                <span>-</span>
                              )
                            })()
                          ) : (
                            <span>{String(value)}</span>
                          )}
                        </div>
                      ))}
                    </div>
                  ) : (
                    <Text>{item.content || ""}</Text>
                  ))}
              </Col>
              <Col flex="none" style={{ marginLeft: 16 }}>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  {formatTime(item.sendTime)}
                </Text>
              </Col>
            </Row>
          )
        })
      )}
    </div>
  )
})

export default Page
